import { Page, expect } from '@playwright/test'

/**
 * Test helper functions for medical imaging platform e2e tests
 */

export class TestHelpers {
    constructor(private page: Page) { }

    /**
     * Navigate to homepage and wait for it to load
     */
    async goToHomepage() {
        await this.page.goto('/')
        await expect(this.page.getByText('数据集选择')).toBeVisible()
    }

    /**
     * Select a dataset by name
     */
    async selectDataset(datasetName: string) {
        await this.page.getByText(datasetName).first().click()
        await expect(this.page).toHaveURL(/\/dataset\/\d+/)
    }

    /**
     * Navigate to a specific task
     */
    async navigateToTask(datasetName: string, taskName: string) {
        await this.selectDataset(datasetName)
        await this.page.getByText(taskName).click()
        await expect(this.page).toHaveURL(/\/task\/\d+\//)
    }

    /**
     * Wait for viewer to load
     */
    async waitForViewerLoad() {
        await expect(this.page.locator('.viewer-3d, .viewer-2d')).toBeVisible()
        await expect(this.page.locator('canvas')).toBeVisible()
    }

    /**
     * Adjust zoom level
     */
    async adjustZoom(direction: 'in' | 'out', times: number = 1) {
        const button = direction === 'in'
            ? this.page.getByRole('button', { name: /zoom-in/i })
            : this.page.getByRole('button', { name: /zoom-out/i })

        for (let i = 0; i < times; i++) {
            await button.click()
        }
    }

    /**
     * Get current zoom percentage
     */
    async getCurrentZoom(): Promise<number> {
        const zoomText = await this.page.locator('text=/\\d+%/').textContent()
        return parseInt(zoomText?.replace('%', '') || '100')
    }

    /**
     * Click on canvas at specific position
     */
    async clickCanvas(panelName: string, x: number, y: number) {
        const panel = this.page.locator('.viewer-panel').filter({ hasText: panelName })
        const canvas = panel.locator('canvas')
        await canvas.click({ position: { x, y } })
    }

    /**
     * Execute a task with parameters
     */
    async executeTask(parameters: Record<string, string | number> = {}) {
        // Set parameters
        for (const [key, value] of Object.entries(parameters)) {
            const input = this.page.locator(`input[placeholder*="${key}"], input[aria-label*="${key}"]`)
            if (await input.isVisible()) {
                await input.fill(String(value))
            }
        }

        // Click execute button
        const executeButton = this.page.getByRole('button', { name: /开始执行|执行任务/i })
        await executeButton.click()
    }

    /**
     * Wait for task completion
     */
    async waitForTaskCompletion(timeout: number = 30000) {
        await expect(this.page.getByText('任务执行完成')).toBeVisible({ timeout })
    }

    /**
     * Mock API responses for testing
     */
    async mockApiResponses() {
        // Mock datasets API
        await this.page.route('**/api/datasets', async route => {
            await route.fulfill({
                status: 200,
                contentType: 'application/json',
                body: JSON.stringify([
                    {
                        id: '1',
                        name: '胸部CT',
                        description: '胸部CT影像数据集',
                        type: '3D',
                        imageCount: 100,
                        size: 1024 * 1024 * 100
                    },
                    {
                        id: '2',
                        name: '脑部MRI',
                        description: '脑部MRI影像数据集',
                        type: '3D',
                        imageCount: 80,
                        size: 1024 * 1024 * 80
                    }
                ])
            })
        })

        // Mock image data API
        await this.page.route('**/api/images/**', async route => {
            await route.fulfill({
                status: 200,
                contentType: 'application/json',
                body: JSON.stringify({
                    id: 'image-1',
                    type: '3D',
                    format: 'DICOM',
                    dimensions: { width: 512, height: 512, depth: 100 },
                    windowCenter: 400,
                    windowWidth: 1600
                })
            })
        })

        // Mock task execution API
        await this.page.route('**/api/tasks/start', async route => {
            await route.fulfill({
                status: 200,
                contentType: 'application/json',
                body: JSON.stringify({
                    success: true,
                    taskId: 'task-123',
                    status: 'running'
                })
            })
        })

        // Mock task status API
        await this.page.route('**/api/tasks/*/status', async route => {
            await route.fulfill({
                status: 200,
                contentType: 'application/json',
                body: JSON.stringify({
                    id: 'task-123',
                    status: 'completed',
                    progress: 100,
                    message: 'Task completed successfully'
                })
            })
        })
    }

    /**
     * Check if element has specific CSS class
     */
    async hasClass(selector: string, className: string): Promise<boolean> {
        const element = this.page.locator(selector)
        const classes = await element.getAttribute('class')
        return classes?.includes(className) || false
    }

    /**
     * Wait for loading to complete
     */
    async waitForLoadingComplete() {
        await expect(this.page.locator('.ant-spin')).not.toBeVisible()
    }

    /**
     * Take screenshot for debugging
     */
    async takeScreenshot(name: string) {
        await this.page.screenshot({
            path: `tests/screenshots/${name}-${Date.now()}.png`,
            fullPage: true
        })
    }

    /**
     * Simulate network delay
     */
    async simulateNetworkDelay(delay: number = 1000) {
        await this.page.route('**/*', async route => {
            await new Promise(resolve => setTimeout(resolve, delay))
            await route.continue()
        })
    }

    /**
     * Check accessibility
     */
    async checkAccessibility() {
        // Check for proper heading structure
        const headings = this.page.locator('h1, h2, h3, h4, h5, h6')
        const headingCount = await headings.count()
        expect(headingCount).toBeGreaterThan(0)

        // Check for alt text on images
        const images = this.page.locator('img')
        const imageCount = await images.count()

        for (let i = 0; i < imageCount; i++) {
            const img = images.nth(i)
            const alt = await img.getAttribute('alt')
            expect(alt).toBeTruthy()
        }

        // Check for proper button labels
        const buttons = this.page.locator('button')
        const buttonCount = await buttons.count()

        for (let i = 0; i < buttonCount; i++) {
            const button = buttons.nth(i)
            const text = await button.textContent()
            const ariaLabel = await button.getAttribute('aria-label')
            expect(text || ariaLabel).toBeTruthy()
        }
    }

    /**
     * Test responsive design at different breakpoints
     */
    async testResponsiveDesign() {
        const breakpoints = [
            { name: 'mobile', width: 375, height: 667 },
            { name: 'tablet', width: 768, height: 1024 },
            { name: 'desktop', width: 1920, height: 1080 }
        ]

        for (const breakpoint of breakpoints) {
            await this.page.setViewportSize({
                width: breakpoint.width,
                height: breakpoint.height
            })

            // Check that main elements are still visible
            await expect(this.page.getByText('数据集选择')).toBeVisible()

            // Take screenshot for visual comparison
            await this.takeScreenshot(`responsive-${breakpoint.name}`)
        }
    }

    /**
     * Simulate user workflow
     */
    async simulateCompleteWorkflow() {
        // 1. Start at homepage
        await this.goToHomepage()

        // 2. Select dataset
        await this.selectDataset('胸部CT')

        // 3. Navigate to task
        await this.page.getByText('病灶检测').click()

        // 4. Configure parameters
        await this.executeTask({ '阈值': 0.7, '最大检测数': 5 })

        // 5. Wait for completion
        await this.waitForTaskCompletion()

        // 6. View results
        await this.page.getByText('查看结果').click()

        // 7. Export results
        await this.page.getByRole('button', { name: /导出结果/i }).click()
    }
}

/**
 * Create test helpers instance
 */
export function createTestHelpers(page: Page): TestHelpers {
    return new TestHelpers(page)
}

/**
 * Common test data
 */
export const testData = {
    datasets: [
        { id: '1', name: '胸部CT', type: '3D' },
        { id: '2', name: '脑部MRI', type: '3D' },
        { id: '3', name: '腹部CT', type: '3D' },
        { id: '4', name: '心脏超声', type: '2D' },
        { id: '5', name: '乳腺X光', type: '2D' }
    ],
    tasks: [
        { name: '病灶检测', type: 'detection' },
        { name: '病灶分类', type: 'classification' },
        { name: '器官分割', type: 'segmentation' }
    ],
    parameters: {
        detection: { '阈值': 0.5, '最大检测数': 10 },
        classification: { '置信度': 0.8 },
        segmentation: { '平滑度': 0.3 }
    }
}